package com.zjzywl.smoke.controller;

import com.zjzywl.smoke.config.AppConfig;
import com.zjzywl.smoke.entity.KeyPersonnel;
import com.zjzywl.smoke.entity.WallDoor;
import com.zjzywl.smoke.util.WebResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.UUID;

@RestController
@RequestMapping(value = "/wallDoor")
public class WallDoorController extends BaseController {
    @Autowired
    private AppConfig appConfig;
    // 同步锁对象
    Object obj = new Object();

    // 保存老墻門信息
    @PostMapping(value = "/save")
    public WebResult save( WallDoor wallDoor, MultipartFile file,@RequestParam("orgId") Integer orgId) {
        try {
            if (file != null) {
                String photoUrl = executeUpload(file, "building");
                wallDoor.setPhotoUrl(photoUrl);
            }
            ResponseEntity<WallDoor> history = appConfig.restTemplate()
                    .postForEntity(appConfig.getGetDataIp() + "/wallDoor/save?orgId="+orgId , wallDoor, WallDoor.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            // 打印出错
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 删除老墻門信息
    @DeleteMapping(value = "/del")
    public WebResult delete(@RequestParam("id") Integer id) {
        try {
            appConfig.restTemplate().delete(appConfig.getGetDataIp() + "/wallDoor/del?id=" + id);
            return WebResult.OK();
        } catch (Exception e) {
            // 打印出错
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }

    }

    // 显示老墻門信息列表
    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    @ResponseBody
    public WebResult getList(HttpServletRequest request) {
        try {
            String userId = "1";
            System.out.println(appConfig.getGetDataIp()
                    + "/wallDoor/getList?userId=" + userId + "&" + URLDecoder.decode(request.getQueryString(), "utf-8"));
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
                    + "/wallDoor/getList?userId=" + userId + "&" + URLDecoder.decode(request.getQueryString(), "utf-8"),
                    Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            // 打印出错
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

   // 按照老墙门地址模糊搜索
    @GetMapping("/findLikeByAddress")
    @ResponseBody
    public WebResult findLikeByName( @RequestParam(value = "address", required = false) String address) throws ParseException, IOException {
        try {
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
                    + "/wallDoor/findLikeByAddress?address=" + address , Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 按照地址和社区搜索
    @GetMapping("/findLikeByAddressAndOrg")
    @ResponseBody
    public WebResult findLikeByAddressAndOrg( @RequestParam("address")String address,@RequestParam("orgId")String orgId) throws ParseException, IOException {
        try {
            System.out.println(appConfig.getGetDataIp()
                    + "/wallDoor/findLikeByAddressAndOrg?address=" + address+"&orgId="+orgId);
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
                    + "/wallDoor/findLikeByAddressAndOrg?address=" + address+"&orgId="+orgId , Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }
//
//    // 获取所有楼宇信息，在地图上画点
//    @GetMapping("/getAllBuildings")
//    @ResponseBody
//    public WebResult getAllBuildings(@RequestParam(value = "type", required = false) Integer type) {
//        try {
//            String userId = this.getUserId();
//            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
//                    appConfig.getGetDataIp() + "/building/getAllBuildings/" + userId + "?type=" + type, Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 获取楼宇巡检列表
//    @GetMapping("/getBuildingInspectionRecord")
//    @ResponseBody
//    public WebResult getBuildings(HttpServletRequest request) {
//        try {
//            String userId = this.getUserId();
//            ResponseEntity<Object> history = appConfig.restTemplate()
//                    .getForEntity(appConfig.getGetDataIp() + "/building/getBuildingInspectionRecord?userId=" + userId
//                            + "&" + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 添加楼宇巡检 微信小程序提交
//    @PostMapping("/save/buildingInspectionRecord")
//    public WebResult saveGetBuildingInspectionRecord(
//            @RequestParam("buildingInspectionRecord") String buildingInspectionRecord,
//            @RequestParam("orgId") Integer orgId) throws ParseException, IOException {
//        try {
//            String name = null;
//            if (buildingInspectionRecord != null && !"".equals(buildingInspectionRecord)) {
//                name = buildingInspectionRecord.substring(1, buildingInspectionRecord.length() - 1);
//            }
//            List<BuildingInspectionRecord> jsonToList = jsonToList(name, BuildingInspectionRecord.class);
//            ResponseEntity<BuildingInspectionRecord> history = appConfig.restTemplate().postForEntity(
//                    appConfig.getGetDataIp() + "/building/save/buildingInspectionRecord?orgId=" + orgId, jsonToList,
//                    BuildingInspectionRecord.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 添加楼宇巡检（提交无问题的接口） 微信小程序提交
//    @PostMapping("/save/buildingInspectionRecordNoProblem")
//    public WebResult saveBuildingInspectionRecordNoProblem(
//            @RequestParam("buildingInspectionRecord") String buildingInspectionRecord,
//            @RequestParam("orgId") Integer orgId) {
//        try {
//            String name = null;
//            if (buildingInspectionRecord != null && !"".equals(buildingInspectionRecord)) {
//                name = buildingInspectionRecord.substring(1, buildingInspectionRecord.length() - 1);
//            }
//            List<BuildingInspectionRecord> jsonToList = jsonToList(name, BuildingInspectionRecord.class);
//            ResponseEntity<BuildingInspectionRecord> history = appConfig.restTemplate().postForEntity(
//                    appConfig.getGetDataIp() + "/building/save/buildingInspectionRecordNoProblem?orgId=" + orgId,
//                    jsonToList.get(0), BuildingInspectionRecord.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 添加楼宇巡检照片 微信小程序提交
//    @PostMapping("/save/buildingInspectionRecordPhoto")
//    public WebResult saveGetbuildingInspectionRecordPhoto(
//            @RequestParam("buildingInspectionRecordId") Integer buildingInspectionRecordId, MultipartFile file,
//            @RequestParam("trouble") Integer trouble) throws ParseException, IOException {
//        try {
//            while (true) {
//                synchronized (obj) {
//                    try {
//                        String photoUrl = executeUpload(file, "buildingInspectionRecord");
//                        ResponseEntity<BuildingInspectionRecord> history = appConfig.restTemplate()
//                                .getForEntity(appConfig.getGetDataIp()
//                                        + "/building/save/buildingInspectionRecordPhoto?buildingInspectionRecordId="
//                                        + buildingInspectionRecordId + "&photoUrl=" + photoUrl + "&trouble=" + trouble,
//                                        BuildingInspectionRecord.class);
//                        return WebResult.OK(history);
//                    } catch (InterruptedException e) {
//                        // TODO Auto-generated catch block
//                        e.printStackTrace();
//                    }
//                }
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    /**
//     * json 转 List<T>
//     */
//    public static List<BuildingInspectionRecord> jsonToList(String jsonString, Class<BuildingInspectionRecord> clazz) {
//        @SuppressWarnings("unchecked")
//        List<BuildingInspectionRecord> ts = (List<BuildingInspectionRecord>) JSONArray.parseArray(jsonString, clazz);
//        return ts;
//    }
//    // // 添加楼宇巡检 微信小程序提交
//    // @PostMapping("/save/buildingInspectionRecord")
//    // public WebResult saveBuildingInspectionRecord(@RequestBody
//    // List<BuildingInspectionRecord> buildingInspectionRecord,
//    // @RequestParam("orgId") Integer orgId) throws ParseException, IOException {
//    // try {
//    // ResponseEntity<BuildingInspectionRecord> history =
//    // appConfig.restTemplate().postForEntity(
//    // appConfig.getGetDataIp() + "/building/save/buildingInspectionRecord?orgId=" +
//    // orgId,
//    // buildingInspectionRecord, BuildingInspectionRecord.class);
//    // return WebResult.OK(history);
//    // } catch (Exception e) {
//    // e.printStackTrace();
//    // return WebResult.FAIL(e.toString());
//    // }
//    // }
//
    /*
     * 图片上传方法
     *
     */
    private String executeUpload(MultipartFile file, String code) throws Exception {
        String uploadDir = getUploadDir() + code + "/";
        // 如果文件不存在，自动创建文件夹
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                logger.error("创建上传目录失败");
            }
        }
        if (file != null) {
            // 文件后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 上传文件名
            String filename = UUID.randomUUID() + suffix;
            // 服务器端保存的文件对象
            File serverFile = new File(uploadDir + filename);
            // 将上传到的文件写入到服务器
            file.transferTo(serverFile);
            return "/upload/" + code + "/" + filename;
        }
        return null;
    }
//
//    // 获取楼层巡检详情
//    @GetMapping("/getBuildingInspectionRecordDetails")
//    @ResponseBody
//    public WebResult getBuildingInspectionRecordDetails(HttpServletRequest request) {
//        try {
//            String userId = "admin";
//            ResponseEntity<Object> history = appConfig.restTemplate()
//                    .getForEntity(appConfig.getGetDataIp() + "/building/getBuildingInspectionRecordDetails?userId="
//                            + userId + "&" + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 获取楼层巡检详情
//    @GetMapping("/getBuildingInspectionRecordDetailsByBuildingName")
//    @ResponseBody
//    public WebResult getBuildingInspectionRecordDetailsByBuildingName(HttpServletRequest request) {
//        try {
//            String userId = "admin";
//            ResponseEntity<Object> history = appConfig.restTemplate()
//                    .getForEntity(appConfig.getGetDataIp()
//                            + "/building/getBuildingInspectionRecordDetailsByBuildingName?userId=" + userId + "&"
//                            + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 获取楼层隐患
//    @GetMapping("/getFloorHiddenDanger")
//    public WebResult getFloorHiddenDanger(HttpServletRequest request) {
//        try {
//            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
//                    + "/building/getFloorHiddenDanger?" + URLDecoder.decode(request.getQueryString(), "utf-8"),
//                    Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 巡检详情隐患图解详情
//    @GetMapping("/getFloorHiddenDangerGraphic")
//    public WebResult getFloorHiddenDangerGraphic(@RequestParam("uuid") String uuid) {
//        try {
//            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
//                    appConfig.getGetDataIp() + "/building/getFloorHiddenDangerGraphic?uuid=" + uuid, Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 主页隐患图解详情
//    @GetMapping("/getFloorHiddenDangerGraphicByOrgId")
//    public WebResult getFloorHiddenDangerGraphicByOrgId() {
//        try {
//            String userId = this.getUserId();
//            ResponseEntity<Object> list = appConfig.restTemplate().getForEntity(
//                    appConfig.getGetDataIp() + "/building/getFloorHiddenDangerGraphicByOrgId?userId=" + userId,
//                    Object.class);
//            return WebResult.OK(list);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 异常违规项 接口
//    @GetMapping("/getExceptionViolation")
//    public WebResult getExceptionViolation() {
//        try {
//            String userId = this.getUserId();
//            ResponseEntity<Object> list = appConfig.restTemplate().getForEntity(
//                    appConfig.getGetDataIp() + "/building/getExceptionViolation?userId=" + userId, Object.class);
//            return WebResult.OK(list);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 异常分布表接口
//    @GetMapping("/getExceptionDistribution")
//    @ResponseBody
//    public WebResult getExceptionDistribution(HttpServletRequest request) {
//        try {
//            String userId = this.getUserId();
//            ResponseEntity<Object> history = appConfig.restTemplate()
//                    .getForEntity(appConfig.getGetDataIp() + "/building/getExceptionDistribution?userId=" + userId + "&"
//                            + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 全区巡检结果
//    @GetMapping("/getInspectionResults")
//    public WebResult getInspectionResults() {
//        try {
//            String userId = this.getUserId();
//            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
//                    appConfig.getGetDataIp() + "/building/getInspectionResults?userId=" + userId, Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 异常分布表根据地址或上报人查询接口
//    @GetMapping("/getExceptionDistributionSearch")
//    public WebResult getExceptionDistributionSearch(
//            @RequestParam(value = "queryContent", required = false) String queryContent,
//            @RequestParam(value = "trouble", required = false) Integer trouble) {
//        try {
//            String userId = this.getUserId();
//            ResponseEntity<Object> history = appConfig.restTemplate()
//                    .getForEntity(appConfig.getGetDataIp() + "/building/getExceptionDistributionSearch?userId=" + userId
//                            + "&queryContent=" + queryContent + "&trouble=" + trouble, Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 首页数据统计接口
//    @GetMapping("/getDataStatistics")
//    public WebResult getDataStatistics() {
//        try {
//            String userId = this.getUserId();
//            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
//                    appConfig.getGetDataIp() + "/building/getDataStatistics?userId=" + userId, Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 获取正常建筑物，异常建筑物的数量
//    @GetMapping("/getStateQuantityOfBuildings")
//    public WebResult getStateQuantityOfBuildings() {
//        try {
//            String userId = this.getUserId();
//            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
//                    appConfig.getGetDataIp() + "/building/getStateQuantityOfBuildings?userId=" + userId, Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    @ApiOperation("月报表柱状统计图接口")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "communityName", value = "小区名称", required = true, paramType = "query", dataType = "String"),
//            @ApiImplicitParam(name = "belongRegion", value = "所属社区", required = true, paramType = "query", dataType = "String"),
//            @ApiImplicitParam(name = "userId", value = "登陆人Id", required = true, paramType = "query", dataType = "int") })
//    @GetMapping(value = "/columns")
//    public WebResult<List<Columns>> columns(HttpServletRequest request) {
//        try {
//            String userId = this.getUserId();
//            System.out.println(appConfig.getGetDataIp() + "/building/columns?userId=" + userId + "&"
//                    + URLDecoder.decode(request.getQueryString(), "utf-8"));
//            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
//                    + "/building/columns?userId=" + userId + "&" + URLDecoder.decode(request.getQueryString(), "utf-8"),
//                    Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }
//
//    // 月报表隐患图解详情
//    @GetMapping("/getPieChart")
//    public WebResult getPieChart(HttpServletRequest request) {
//        try {
//            String userId = this.getUserId();
//            ResponseEntity<Object> history = appConfig.restTemplate()
//                    .getForEntity(appConfig.getGetDataIp() + "/building/getPieChart?userId=" + userId + "&"
//                            + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
//            return WebResult.OK(history);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return WebResult.FAIL(e.toString());
//        }
//    }

}
